package com.gr.labbackend.service.Impl.editor;

import com.alibaba.fastjson.JSONObject;
import com.gr.labbackend.service.editor.ImageUploadService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

@Service
public class ImageUploadServiceImpl implements ImageUploadService {

    // 从配置文件中读取上传目录路径
    @Value("${file.upload-dir}")
    private String uploadDir;

    @Override
    public JSONObject uploadImage(MultipartFile file) {
        JSONObject resp = new JSONObject();

        if (file.isEmpty()) {
            resp.put("errno", 1);
            resp.put("message", "没有上传图片");
            return resp;
        }

        // 生成文件名
        String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
        String filePath = uploadDir + File.separator + fileName;  // 使用 uploadDir 配置的路径

        // 将图片保存到指定的本地目录
        try {
            Files.copy(file.getInputStream(), Paths.get(filePath));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 返回图片的 URL（假设在本地开发中，图片通过 `http://localhost:8080/uploads/{fileName}` 访问）
        String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
                .path("/uploads/")
                .path(fileName)
                .toUriString();

        resp.put("errno", 0);
        JSONObject data = new JSONObject();
        data.put("url", fileDownloadUri);
        resp.put("data", data);
        return resp;
    }
}
